package resources.NTree;

import resources.NTree.*;

public class SList {
	SNode firstNode;

	public SList() {
		firstNode = null;
	}

	public void addElement(Object value) {
		if (firstNode == null)
			firstNode = new SNode(value);
		else {
			SNode aux = firstNode;
			while (aux.next() != null)
				aux = aux.next();

			aux.next(new SNode(value));
		}
	}

	public int size() {
		int size = 0;
		SNode aux = firstNode;
		while (aux != null) {
			aux = aux.next();
			size++;
		}
		return size;
	}

	public Object elementAt(int index) {
		if ((index <= size()) & (index > 0)) {
			SNode aux = firstNode;

			for (int i = 1; i < index; i++)
				aux = aux.next();

			return aux.value();
		} else
			return null;
	}

	public boolean equals(SList aList) {
		if (size() == aList.size()) {
			int index = 1;
			SNode aux = firstNode;
			boolean equals = true;
			while ((aux != null) & equals) {
				if ((aList.elementAt(index)).equals(aux.value())) {
					index++;
					aux = aux.next();
				} else
					equals = false;
			}
			return equals;
		}
		return false;
	}

	public boolean contains(Object aObject) {
		boolean includes = false;
		SNode aux = firstNode;
		while ((aux != null) & (!includes))
			if (aObject.equals(aux.value()))
				includes = true;
			else
				aux = aux.next();
		return includes;
	}

	public Object firstElement() {
		if (!isEmpty())
			return firstNode.value();
		else
			return null;
	}

	public Object lastElement() {
		if (!isEmpty()) {
			SNode aux = firstNode;
			while (aux.next != null)
				aux = aux.next();

			return aux.value();
		} else
			return null;
	}

	public void atPut(int index, Object value) {
		if ((index > 0) & (index <= size()) & (!isEmpty())) {
			if (index != 1) {
				SNode aux = firstNode;
				for (int i = 1; i < (index - 1); i++)
					aux = aux.next();

				SNode newNode = new SNode(value);

				if (aux.next() != null)
					newNode.next(aux.next());

				aux.next(newNode);
			} else {
				SNode newNode = new SNode(value);
				newNode.next(firstNode);
				firstNode = newNode;
			}

		}
	}

	public boolean isEmpty() {
		return (firstNode == null);
	}

	public void removeElement(Object anObject) {
		SNode aux = firstNode;
		SNode pre = firstNode;

		while ((aux != null) & (!anObject.equals(aux.value()))) {
			pre = aux;
			aux = aux.next();
		}

		if (aux != null)
			if (aux != firstNode)
				pre.next(aux.next());
			else
				firstNode = firstNode.next();
	}

	public void removeFirstElement() {
		if (!isEmpty()) {
			firstNode = firstNode.next();
		}
	}

	public void removeLastElement() {
		if (!isEmpty()) {
			SNode aux = firstNode;
			SNode pre = firstNode;

			while (aux.next() != null) {
				pre = aux;
				aux = aux.next();
			}

			if (aux != firstNode)
				pre.next(null);
			else
				firstNode = null;
		}

	}

}